<?php

namespace Fwadmin\Model;

use Think\Model;

class MemberModel extends Model {

    /*
     * 显示用户名
     */
    public function show_name($member_id) {
        $row = $this->field('username,phone,email,nickname')->where(array('member_id'=>$member_id))->find();
        if(!empty($row)) {
            if(!empty($row['username'])) {
                return $row['username'];
            } elseif (!empty($row['phone'])) {
                return $row['phone'];
            } elseif (!empty($row['email'])) { 
                return $row['email'];
            } elseif (!empty($row['nickname'])) { 
                return $row['nickname'];
            } else {
                return $member_id;
            }
        } else {
            return '无此用户';
        }
    }
    
    /*
     * 根据名称获得会员ID
     */
    public function get_member_id($name) {
        return $this->where(array('email|phone|username'=>$name))->getField('member_id');
    }
    
    /*
     * 删除会员，其实是没有删除，只是不能用
     * @param int $member_id 会员ID
     */
    public function del($member_id) {
        return $this->where('member_id='.$member_id)->setField('status',3);
    }
    
    /**
     * 注册用户
     */
    public function register($phone, $username, $password) {
        //$data['email'] = $email;
        $data['phone'] = $phone;
        $data['username'] = $username;
        $data['password'] = strongmd5($password);
        $data['point'] = 0;
        $data['experience'] = 0;
        $data['money'] = 0;
        $data['level_id'] = 1;
        $data['is_valid_phone'] = 0;
        $data['is_valid_email'] = 0;
        $data['status'] = 1;
        $data['create_time'] = time();
        $member_id = $this->add($data);
        if ($member_id > 0) {
            //增加会员信息表记录
            $MemberInfoObj = new \Fwadmin\Model\MemberInfoModel();
            $MemberInfoObj->member_id = $member_id;
            $MemberInfoObj->create_ip = get_client_ip();
            $MemberInfoObj->add();
            //注册赠送积分
            $MemberPointObj = new \Fwadmin\Model\MemberPointModel();
            $config = S('config');
            $MemberPointObj->add_by_register($member_id, $config['point_register']);
        }
        return $member_id;
    }
	
	
		
	  /**
     * 绑定注册手机用户
     */
    public function register_bind_phone($phone, $password) {
        //绑定的类别和值
		$login_bind_name = session('login_bind_name');//绑定的值，如openid
	    $login_bind_type = session('login_bind_type');//绑定的类别
		if($login_bind_name!=''){
		switch($login_bind_type){
		case 1:
        $map['login_weixin'] = $login_bind_name;$data2['login_weixin'] = $login_bind_name;$bind_type='login_weixin';
        break;
        case 2:
         $map['login_weibo'] = $login_bind_name;$data2['login_weibo'] = $login_bind_name;$bind_type='login_weibo';
        break;
        default:
        $map['login_weixin'] = $login_bind_name;$data2['login_weixin'] = $login_bind_name;$bind_type='login_weixin';
		
		  }
		}
		
		 
        $data['phone'] = $phone;
        $data['password'] = strongmd5($password);
		$model = $this->where(Array('phone'=>$phone))->find();//判断是否有
		if($model){
		 $this->where(Array('phone'=>$phone))->setField($data2);
		 return $model['member_id'];
		exit();
		}elseif($password==''){
		 return '0';
		 exit();
		}
		/******如果member表不存在该手机号，那么就需要添加一条会员数据,并把登录接口类别添加到表里***/
		$data[$bind_type] = $login_bind_name;
		$data['point'] = 0;
		$data['nickname'] =  session('nickname');
        $data['experience'] = 0;
        $data['money'] = 0;
        $data['level_id'] = 1;
        $data['is_valid_phone'] = 0;
        $data['is_valid_email'] = 0;
        $data['status'] = 1;
        $data['create_time'] = time();
        $member_id = $this->add($data);//$this->where($map)->save($data);
         if ($member_id > 0) {
            //增加会员信息表记录
            $MemberInfoObj = new \Fwadmin\Model\MemberInfoModel();
            $MemberInfoObj->member_id = $member_id;
            $MemberInfoObj->create_ip = get_client_ip();
            $MemberInfoObj->add();
            //注册赠送积分
            $MemberPointObj = new \Fwadmin\Model\MemberPointModel();
            $config = S('config');
            $MemberPointObj->add_by_register($member_id, $config['point_register']);
        }
        return $member_id;
    }
	
	

	
    
    /**
     * 判断用户名是否存在，存在返回1
     * @param string $username 昵称
     * @param int $member_id 排除用户ID
     */
    public function existUsername($username, $member_id) {
        return $this->where(array('username' => $username, 'member_id' => array('neq', $member_id)))->count();
    }

    /**
     * 判断邮箱是否存在，存在返回1
     * @param string $email 邮箱
     * @param int $member_id 排除用户ID
     */
    public function existEmail($email, $member_id) {
        return $this->where(array('email' => $email, 'member_id' => array('neq', $member_id)))->count();
    }

    /**
     * 判断手机是否存在，存在返回1
     * @param string $phone 昵称
     * @param int $member_id 排除用户ID
     */
    public function existPhone($phone, $member_id) {
        return $this->where(array('phone' => $phone, 'member_id' => array('neq', $member_id)))->count();
    }
    
    /**
     * 搜索符合条件的记录
     * @param <type> $conditions 条件数组
     * @param string $order 排序字段
     * @param bool $export 是否导出excel
     * @param int $pagesize 分页数
     */
    public function search($conditions = array(), $order = 'member_id desc', $export = false, $pagesize = 0) {
        $map = $conditions;
        if(empty($map['status'])) {
            $map['status'] = array('neq',3);
        }
		foreach($conditions as $k =>$v){
		if($k=='phone') {
		  $map['phone'] = array('like','%'.$conditions['phone'].'%'); 
		}else{
		$map[$k] = $v;
		}
	 }
        if (!$export) {
            $count = $this->where($map)->count(); // 查询满足要求的总记录数
            if ($pagesize == 0) {
                $pagesize = C('PAGE_NUM');
            }
            $Page = new \Think\Page($count, $pagesize); // 实例化分页类 传入总记录数和每页显示的记录数
            //分页跳转的时候保证查询条件
            foreach ($conditions as $key => $val) {
                $Page->parameter[$key] = urlencode($val);
            }
            $show = $Page->show(); // 分页显示输出
            // 进行分页数据查诟 注意limit 方法癿参数要使用Page 类的属性
            $list = $this->where($map)->order($order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
            return array(
                'list' => $list,
                'page' => $show
            );
        } else {
            return $this->where($map)->order($order)->select();
        }
    }
    
    /**
     * 获取会员积分
     * @param int $member_id 会员ID
     * @return int 积分
     */
    public function get_point($member_id) {
        return $this->getFieldByMemberId($member_id,'point');
    }
    
    /**
     * 修改积分
     * @param int $member_id 会员ID
     * @param int $point 修改的积分
     * @return int 返回修改后的积分
     */
    public function set_point($member_id,$point) {
        $point_now = $this->get_point($member_id);
        $point_end = $point_now + $point;
        $this->where('member_id='.$member_id)->setField('point',$point_end);
        return $point_end;
    }
    
    /**
     * 获取会员余额
     * @param int $member_id 会员ID
     * @return int 余额
     */
    public function get_money($member_id) {
        return $this->getFieldByMemberId($member_id,'money');
    }
    
    /**
     * 修改余额
     * @param int $member_id 会员ID
     * @param int $money 修改的余额
     * @return int 返回修改后的余额
     */
    public function set_money($member_id,$money) {
        $money_now = $this->get_money($member_id);
        $money_end = $money_now + $money;
        $this->where('member_id='.$member_id)->setField('money',$money_end);
        return $money_end;
    }
    
    /**
     * 获取会员经验值
     * @param int $member_id 会员ID
     * @return int 经验值
     */
    public function get_experience($member_id) {
        return $this->getFieldByMemberId($member_id,'experience');
    }  
    
    /**
     * 修改积分
     * @param int $member_id 会员ID
     * @param int $experience 修改的经验值
     * @return int 返回修改后的积分
     */
    public function set_experience($member_id,$experience) {
        $experience_now = $this->get_experience($member_id);
        $experience_end = $experience_now + $experience;
        $this->where('member_id='.$member_id)->setField('experience',$experience_end);
        //$this->update_level($member_id);
        return $experience_end;
    }
    
    /**
     * 更新会员等级
     * @param type $member_id
     */
    public function update_level($member_id) {
        $experience = $this->get_experience($member_id);
        $MemberLevel = new \Home\Model\MemberLevelModel();
        $member_level = $MemberLevel->get_level($experience);
        return $this->where('member_id='.$member_id)->setField('level_id',$member_level); 
    }
    
        /**
     * 更新会员等级
     * @param type $member_id
     */
    public function update_level_all() {
        $member = $this->field('member_id')->select();
        print($member);
        $count = 0;
        foreach($member as $m) {
            $count += $this->update_level($m['member_id']);
        }
        echo $count;
    }
    
    /**
     * 统计注册
     * @param int $pagesize 分页数
     */
    public function tongji_zhuce($conditions = array(), $pagesize = 100) {
        $where = ' where 1=1';
        if(!empty($conditions['btime'])) {
           $btime = strtotime($conditions['btime'].' 00:00:00');
           $where .= ' and create_time>='.$btime;
        }
        if(!empty($conditions['etime'])) {
           $etime = strtotime($conditions['etime'].' 23:59:59');
           $where .= ' and create_time<'.$etime;
        }
        $data_format = "DATE_FORMAT(from_unixtime(create_time),'%Y-%m-%d')";
        if(!empty($conditions['type'])) {
            if($conditions['type'] == '月') {
                $data_format = "DATE_FORMAT(from_unixtime(create_time),'%Y-%m')";
            } elseif ($conditions['type'] == '年') {
                $data_format = "DATE_FORMAT(from_unixtime(create_time),'%Y')";
            }
        }
        $sql = "select ".$data_format." as day,count(1) as num from ".C('DB_PREFIX')."member ".$where." group by day order by day desc limit ".$pagesize;
        $list = $this->query($sql);
        
        $sql_total = "select count(1) as num from ".C('DB_PREFIX')."member ".$where." ";
        $query_total = $this->query($sql_total);
        $total = $query_total[0]['num'];
        $data['list'] = $list;
        $data['total'] = $total;
        return $data;
    }

}
